#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, site 
import re, urllib
import datetime, time
import shutil

import sqlite3dbm

from generator import *
from paneo import *

import web
from sqlobject import *
sqlhub.processConnection = connectionForURI('sqlite://'+ARTICLES_DB)

#render
from web.contrib.template import render_mako

render = render_mako(   directories=[PANEO_ROOT+'/_cms/templates/'],
                        input_encoding='utf-8',
                        output_encoding='utf-8',
                        default_filters=["none_to_blank", "unicode"],
                        encoding_errors='replace', 
                        imports = RENDER_IMPORTS )

class View:

    def __init__(self):
        self.cms = 'home'
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")

    def GET( self ):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        dic.close()

        site_img = {} 
        for ii in range(1,6):
            file = 'site_img%s_file' % ii
            if IMG_CONV :
                src = "/img/site_img%s" % ii
            else:
                src = "/%s/img/site_img%s" % ( PANEO_SITE_DATA_DIR , ii )
            site_img[file] = [ os.path.exists(PANEO_SITE_DATA_DIR + "img/site_img%s" % ii) ,src ]

        return render.home(     
                                cms = self.cms,                        
                                scfg = scfg, 
                                site_img = site_img,
        )



    def POST( self ):
        i = web.input( PAGEMAKE = 'CMS' )

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')

        #SITE CONFIG
        scfg['SITENAME'] = i.SITENAME
        scfg['SITEDESCRIPTION'] = i.SITEDESCRIPTION
        scfg['SITEKEYWORD'] = i.SITEKEYWORD
        scfg['PAGEMAKE'] = i.PAGEMAKE

        _context = {}
        for ii in range(1,6):
            _context['context%s'%ii] = i.get('CONTEXT%s'%ii,'')
        scfg['CONTEXT'] = _context

        #画像
        img_alt = {}
        for ii in range(1,6):
            if i.has_key('site_img%s_file_del' % ii):
                if os.path.exists(PANEO_SITE_DATA_DIR + "img/site_img%s" % ii):
                    os.remove(PANEO_SITE_DATA_DIR + "img/site_img%s" % ii)
            
            f = 'site_img%s_file' % ii
            if i.has_key(f):
                if i[f] != "":
                    fout = open(PANEO_SITE_DATA_DIR + "img/site_img%s" % ii,'wb')
                    fout.write(i[f])
                    fout.close()

            alt = 'site_img%s_alt' % ii
            img_alt[alt] = i[alt]

        scfg['SITEIMAGE'] = img_alt

        dic['siteconfig'] = scfg
        dic.close()

        return self.GET()

